<template>
    <div>
        <div>
            <h1>用户列表</h1>
        </div>
        <div>
             <el-form :inline="true" :model="pageFrom" class="demo-form-inline">
                <el-form-item label="用户名称">
                <el-input v-model="pageFrom.keyWord" placeholder="请输入" clearable />
                </el-form-item>
                <el-form-item>
                <el-button type="primary" @click="onSubmit">搜索</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div style="margin-bottom: 15px;">
            <el-button type="primary" @click="saveUser" :icon="Edit" />
            <el-button type="primary" @click="delsUser" :icon="Delete" />
            <el-button type="primary" @click="sjsUser" :icon="Open" />
        </div>
        <div>
            <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
                 <el-table-column type="selection" width="55" />
                <el-table-column prop="userId" label="用户ID" />
                <el-table-column prop="userName" label="用户账号" />
                <el-table-column prop="userMobile" label="手机号" />
                <el-table-column prop="userStatus" label="用户状态" >
                     <template #default="scope">
                        <el-tag type="success" v-if="scope.row.userStatus == 1">正常</el-tag>
                        <el-tag type="info" v-if="scope.row.userStatus == 2">隐藏</el-tag>
                        <el-tag type="danger" v-if="scope.row.userStatus == 3">危险</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="userEmail" label="地址邮件" />
                <el-table-column prop="nickName" label="真实姓名" />
                <el-table-column prop="userUrl" label="用户头像" >
                    <template #default="scope">
                        <img :src="scope.row.userUrl" width="50px" height="50px" />
                    </template>
                </el-table-column>
                <el-table-column label="操作" >
                     <template #default="scope">
                        <el-button-group class="ml-4">
                            <el-button type="primary" @click="editUser(scope.row)" :icon="Edit" />
                            <el-button type="primary" :icon="Share" />
                            <el-button type="primary" :icon="Delete" />
                        </el-button-group>
                     </template>
                </el-table-column>
            </el-table>
        </div>
        <div style="margin-top: 20px;">
            <el-pagination
            v-model:current-page="pageFrom.pageNum"
            v-model:page-size="pageFrom.pageSize"
            :page-sizes="[100, 200, 300, 400]"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            />
        </div>
        <div>
            <el-dialog v-model="dialogFormVisible" title="用户添加" width="500">
                <el-form :model="form">
                <el-form-item label="用户账号：" :label-width="formLabelWidth">
                    <el-input v-model="form.userName" autocomplete="off" placeholder="请输入用户账号" />
                </el-form-item>
                <el-form-item label="用户密码：" :label-width="formLabelWidth">
                    <el-input v-model="form.passWord" autocomplete="off" placeholder="请输入用户密码" />
                </el-form-item>
                <el-form-item label="手机号：" :label-width="formLabelWidth">
                    <el-input v-model="form.userMobile" autocomplete="off" placeholder="请输入手机号" />
                </el-form-item>
                <el-form-item label="地址邮件：" :label-width="formLabelWidth">
                    <el-input v-model="form.userEmail" autocomplete="off" placeholder="请输入地址邮件" />
                </el-form-item>
                <el-form-item label="真实姓名：" :label-width="formLabelWidth">
                    <el-input v-model="form.nickName" autocomplete="off" placeholder="请输入真实姓名" />
                </el-form-item>
                <el-form-item label="用户头像：" :label-width="formLabelWidth">
                    <el-upload
                        class="avatar-uploader"
                        action="http://127.0.0.1:10010/user/user/minioUpload"
                        :show-file-list="false"
                        :headers="headers"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload"
                    >
                        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                    </el-upload>
                </el-form-item>
                </el-form>
                <template #footer>
                <div class="dialog-footer">
                    <el-button @click="onSave">添 加</el-button>
                    <el-button type="primary" @click="onDelForm">
                    取 消
                    </el-button>
                </div>
                </template>
            </el-dialog>
        </div>
         <div>
            <el-dialog v-model="dialogFormVisibleEdit" title="修改用户" width="500">
                <el-form :model="form">
                <el-form-item label="用户账号：" :label-width="formLabelWidth">
                    <el-input v-model="form.userName" autocomplete="off" placeholder="请输入用户账号" />
                </el-form-item>
                <el-form-item label="用户密码：" :label-width="formLabelWidth">
                    <el-input v-model="form.passWord" autocomplete="off" placeholder="请输入用户密码" />
                </el-form-item>
                <el-form-item label="手机号：" :label-width="formLabelWidth">
                    <el-input v-model="form.userMobile" autocomplete="off" placeholder="请输入手机号" />
                </el-form-item>
                <el-form-item label="地址邮件：" :label-width="formLabelWidth">
                    <el-input v-model="form.userEmail" autocomplete="off" placeholder="请输入地址邮件" />
                </el-form-item>
                <el-form-item label="真实姓名：" :label-width="formLabelWidth">
                    <el-input v-model="form.nickName" autocomplete="off" placeholder="请输入真实姓名" />
                </el-form-item>
                <el-form-item label="用户头像：" :label-width="formLabelWidth">
                    <el-upload
                        class="avatar-uploader"
                        action="http://127.0.0.1:10010/user/user/minioUpload"
                        :show-file-list="false"
                        :headers="headers"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload"
                    >
                        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                    </el-upload>
                </el-form-item>
                </el-form>
                <template #footer>
                <div class="dialog-footer">
                    <el-button @click="onEdit">修 改</el-button>
                    <el-button type="primary" @click="onDelFormEdit">
                    取 消
                    </el-button>
                </div>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { userList, userSave, userDel, userEdit, sjUser } from '../api/api';
import { Delete, Edit, Search, Share, Upload, Open } from '@element-plus/icons-vue'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import { ElMessage } from 'element-plus'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

const tableData = ref([]);
const dialogFormVisible = ref(false)
const multipleSelection = ref<any[]>([])
const ids = ref([])
const dialogFormVisibleEdit = ref(false)
const imageUrl = ref('')
const formLabelWidth = '140px'
const total = ref(0);
const pageFrom = ref({
    pageNum: 1,
    pageSize: 2,
    keyWord: ''
})
// 添加Form
const form = ref({
    userName: '',
    passWord: '',
    userMobile: '',
    userEmail: '',
    nickName: '',
    userUrl: ''
})
// 分页功能
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
  pageFrom.value.pageSize = val;
  loadList();
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
  pageFrom.value.pageNum = val;
  loadList()
}
// 列表多选框
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val
  ids.value = [];
  multipleSelection.value.forEach(mulit => {
    ids.value.push(mulit.userId)
  })
  console.log(ids.value);
}

// 用户列表
const loadList = () => {
    userList(pageFrom.value).then(res => {
        console.log(res);
        
        if (res.data.code == 200) {
            tableData.value = res.data.data.records;
            total.value = res.data.data.total;
        }
    })
}
// 获取token，完成图片上传
const headers = ref({
    token: window.sessionStorage.getItem("token")
})
// 图片上传
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  imageUrl.value = response.data
}
// 图片规格
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

// 添加按钮
const saveUser = () => {
    console.log('添加');
    dialogFormVisible.value = true;
}
// 添加按钮-提交版
const onSave = () => {
    userSave(form.value).then(res => {
        form.value.userUrl = imageUrl.value;
        if (res.data.code == 200) {
            ElMessage.success("添加成功");
            // 刷新列表
            loadList()
            // 关闭对话框
            dialogFormVisible.value = false
            // 添加成功后清空form对象数据
            form.value = {
                userName: '',
                passWord: '',
                userMobile: '',
                userEmail: '',
                nickName: '',
                userUrl: ''
            }
        } else {
            ElMessage.error("添加失败");
            // 刷新列表
            loadList()
            // 关闭对话框
            dialogFormVisible.value = false
            // 添加成功后清空form对象数据
            form.value = {
                userName: '',
                passWord: '',
                userMobile: '',
                userEmail: '',
                nickName: '',
                userUrl: ''
            }
        }
    })
}
// 修改按钮
const editUser = (row: any) => {
    console.log("修改");
    dialogFormVisibleEdit.value = true
    form.value = row
}
// 修改按钮-提交版
const onEdit = () => {
    form.value.userUrl = imageUrl.value
    userEdit(form.value).then(res => {
        if (res.data.code == 200) {
            ElMessage.success("修改成功")
            // 刷新列表
            loadList()
            // 关闭对话框
            dialogFormVisibleEdit.value = false
            // 添加成功后清空form对象数据
            form.value = {
                userName: '',
                passWord: '',
                userMobile: '',
                userEmail: '',
                nickName: '',
                userUrl: ''
            }
        } else {
            ElMessage.error("添加失败");
            // 刷新列表
            loadList()
            // 关闭对话框
            dialogFormVisibleEdit.value = false
            // 添加成功后清空form对象数据
            form.value = {
                userName: '',
                passWord: '',
                userMobile: '',
                userEmail: '',
                nickName: '',
                userUrl: ''
            }
        }
    })
}
// 点击取消，清空添加表单数据
const onDelForm = () => {
    dialogFormVisible.value = false;
     form.value = {
        userName: '',
        passWord: '',
        userMobile: '',
        userEmail: '',
        nickName: '',
        userUrl: ''
    }
}
// 点击取消，清空修改表单数据
const onDelFormEdit = () => {
    dialogFormVisibleEdit.value = false;
     form.value = {
        userName: '',
        passWord: '',
        userMobile: '',
        userEmail: '',
        nickName: '',
        userUrl: ''
    }
}
// 批量删除
const delsUser = () => {
    console.log("删除");
    userDel(ids.value).then(res => {
        if (res.data.code == 200) {
            ElMessage.success("删除成功")
            loadList();
        } else {
            ElMessage.error("删除失败")
        }
    })
}
// 批量上架
const sjsUser = () => {
    console.log("上架")
    sjUser(ids.value).then(res => {
        if (res.data.code == 200) {
            ElMessage.success("修改成功")
            loadList();
        } else {
            ElMessage.error("修改失败")
        }
    })
}
// 查询条件
const onSubmit = () => {
  console.log('submit!')
  loadList()
}

// 页面加载钩子函数
onMounted(() => {
    loadList();
})

</script>

<style scoped>
.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}
</style>